/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package simplepushclient;

import java.io.DataOutputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.Socket;
import javax.swing.JOptionPane;

/**
 *
 * @author Filip
 */
public class Sender{
    private String data;
    private InetAddress dns;
    private int port;
    private boolean showTimeOut;

    public Sender(String[] ip,String data){
        this.data = data;
        this.showTimeOut=true;
        try {
            this.dns = Inet4Address.getByName(ip[0]);
            this.port = Integer.parseInt(ip[1]);
        }catch(Exception e){
            JOptionPane.showMessageDialog(null,"Remote computer isn't online or the connect was "
                + "blocked by a firewall\n\""+e.toString()+"\"\nServer: "+ip[0]+" @ port: "+ip[1]);
            e.printStackTrace();
            System.exit(0);
        }
    }

    public Sender(String[] ip){
        this(ip, null);
    }

    public InetAddress getDns() {
        return dns;
    }

    public void run() {
        Thread t = new Thread(){
            public void run() {
                push();
            }
        };
        t.start();
    }

    public void showTimeOut(boolean showTimeOut) {
        this.showTimeOut = showTimeOut;
    }

    public void setData(String data) {
        this.data = data;
    }

    protected void push() {
        try {
            Socket s = new Socket(dns, port);
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            if (!(data == null || data.isEmpty())) {
                dos.writeUTF(data);
            }
            s.close();
        }catch (Exception ce) {
            if(showTimeOut){
                p("Remote computer isn't online or the connect was "
                + "blocked by a firewall\n\n"+ce.toString()
                +"\nServer: "+dns.toString()+" @ port: "+port);
            }else{
               ce.printStackTrace();
            }
        }
    }
    private static void p(String toString) {
        JOptionPane.showMessageDialog(null, toString);
    }
}
